package com.zhkj.lib.http

import androidx.annotation.CallSuper
import androidx.lifecycle.MutableLiveData

open class ViewModelSubscribeListener<Response : BaseResponse>(
    private val liveData: MutableLiveData<HttpResponse<Response>>?
) : SubscribeListener<Response> {
    @CallSuper
    override fun onStart() {
        with(liveData?.value ?: HttpResponse()) {
            status = HttpResponseStatus.Status.START
            liveData?.postValue(this)
        }
    }

    override fun onSuccess(resp: Response) {
        with(liveData?.value ?: HttpResponse()) {
            status = HttpResponseStatus.Status.SUCCESS
            response = resp
            liveData?.postValue(this)
        }
    }

    @CallSuper
    override fun onFailure(throwable: Throwable) {
        throwable.printStackTrace()
        with(liveData?.value ?: HttpResponse()) {
            status = HttpResponseStatus.Status.FAILURE
            exception = throwable
            liveData?.postValue(this)
        }
    }
}